import axios from 'axios';
import { getAppEnvConfig } from '/@/utils/env.ts';
import { getAuthCache } from '/@/utils/auth.ts';
import { TOKEN_KEY } from '/@/enum/cacheEnum.ts';
import { useMessage } from '/@/hooks/web/useMessage.ts';
import router from '/@/router';
import { useUserStore } from '/@/store/modules/user.ts';
import { getBaseLogin, toLoginByNowPath } from '/@/enum/pageEnum.ts';

const { createMessage } = useMessage();
const { VITE_GLOB_API_URL } = getAppEnvConfig();

const service = axios.create({
    baseURL: VITE_GLOB_API_URL,
    timeout: 50000,
    headers: {
        // 设置后端需要的传参类型
        'Content-Type': 'application/json;charset=UTF-8',
        'X-Access-Token': getAuthCache(TOKEN_KEY),
    },
});
service.interceptors.request.use((config, options) => {
    const userStore = useUserStore();
    const token = userStore.getToken;
    config.headers['X-Access-Token'] = token || getAuthCache(TOKEN_KEY);
    return config;
});
service.interceptors.response.use(
    (response) => {
        return response;
    },
    (error) => {
        if (error.response) {
            console.log('response', error.response);
            switch (error.response.data.code) {
                case 401:
                    // debugger;
                    let path = getBaseLogin();
                    if (!path) {
                        path = toLoginByNowPath(router.currentRoute.value.path);
                    }
                    // createMessage.warn(error.response.data.message);
                    router.replace({
                        path: path,
                    });
            }
        }
        return Promise.reject(error.response.data); // 返回接口返回的错误信息
    }
);
export const get = (url, params = {}) => {
    return new Promise((resolve, reject) => {
        service
            .get(url, { params: params })
            .then((res) => {
                if (res.data.code === 200 || res.data.code === 0) {
                    resolve(res.data);
                } else {
                    reject(res.data);
                }
            })
            .catch((err) => {
                reject(err.data);
            });
    });
};
export const post = (url: string, params: any) =>
    new Promise((resolve, reject) => {
        service
            .post(url, params)
            .then((res: any) => {
                resolve(res.data);
            })
            .catch((err: any) => {
                reject(err);
            });
    });
